<?php
/**
 * Project: AIGC
 * Author: moufer <moufer@163.com>
 * Date: 2024/9/25 23:02
 */

namespace module\user\front\input;

use app\library\validate\CaptchaValidate;
use mof\exception\LogicException;
use mof\Request;

class BindInput
{
    const EMAIL  = 'email';
    const MOBILE = 'mobile';

    protected array $attrs = [
        'type', 'account'
    ];

    public function __construct(protected array $data)
    {
    }

    public static function __make(Request $request): static
    {
        $type = $request->post('type');
        if (static::EMAIL === $type) {
            $rules = [
                'account|邮箱'   => 'require|email|unique:user,email',
                'captcha|验证码' => 'require|emsCaptcha:account,#bind',
            ];
            $message = [
                'account.require'    => '邮箱不能为空',
                'account.unique'     => '邮箱已存在',
                'account.email'      => '邮箱格式不正确',
                'captcha.emsCaptcha' => '验证码不正确',
            ];
        } else if (static::MOBILE === $type) {
            $rules = [
                'account|手机号' => 'require|mobile|unique:user,mobile',
                'captcha|验证码' => 'require|smsCaptcha:account,#bind',
            ];
            $message = [
                'account.require'    => '手机号不能为空',
                'account.unique'     => '手机号已存在',
                'account.email'      => '手机号格式不正确',
                'captcha.emsCaptcha' => '验证码不正确',
            ];
        } else {
            throw new LogicException('未知的绑定类型');
        }

        CaptchaValidate::register();
        $data = $request->withValidate($rules, $message)->post();

        return new self($data);
    }

    public function __get($name)
    {
        return $this->data[$name] ?? null;
    }

}